﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ywxt.NewsPush.Controllers.AttachmentManage
{
    using System.Data;
    using NHibernate;
    using NHibernate.Criterion;
    using DB_NH;

    public class AttachmentController : Controller
    {
        //
        // GET: /Attachment/

        /// <summary>
        /// 根据id获取附件文件，并下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult get(string id)
        {
            #region 获取文件
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var _data_file = session.QueryOver<DB_NH.DB_Model.ywxt.t_attachment>()
                        .Where(c => c.is_valid == 1 && c.att_id == id)
                        .SingleOrDefault();
                    transaction.Commit();

                    if (_data_file != null)
                    {
                        return File(_data_file.att_bytes, "application/octet-stream", Url.Encode(_data_file.att_file_name_original));
                    }
                    else
                    {
                        return Content("文件错误！请确认文件信息。");
                    }
                }
            }
            #endregion
        }

        /// <summary>
        /// 按文件ID删除文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult delete(string id)
        {
            #region 设置文件的可用状态为0
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    string _sql = "UPDATE " + DB_NH.DB_Model.ywxt.t_attachment.TableName + " SET " +
                        DB_NH.DB_Model.ywxt.t_attachment.Columns.is_valid + " = 0 WHERE " +
                        DB_NH.DB_Model.ywxt.t_attachment.Columns.att_id + " = '" + id + "'";
                    var cmd = session.CreateSQLQuery(_sql);
                    if (cmd.ExecuteUpdate() == 1)
                    {

                        transaction.Commit();
                        TempData[ywxt.Common.Common.CONST_TEMPDATA_INF] = "附件删除成功。";
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        transaction.Rollback();
                        TempData[ywxt.Common.Common.CONST_TEMPDATA_INF] = "附件删除失败，请确认参数是否正确。";
                        return RedirectToAction("Index");
                    }
                }
            }
            #endregion
        }
    }
}
